package org.springblade.modules.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.PlanContentSaveDto;
import org.springblade.modules.admin.dto.ai.RobotCreatePlanDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.*;
import org.springblade.modules.admin.mapper.ChatGroupBuildingMapper;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.service.feishu.ILarkMaintenanceService;
import org.springblade.modules.admin.vo.ai.RobotCreatePlanVO;
import org.springblade.modules.admin.vo.ai.RobotPlanDetailVO;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.service.ITenantService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: Sharry
 * @createTime: 2023/5/18 16:40
 * @version: Version-1.0
 */
@Service
@AllArgsConstructor
public class ChatGroupBuildingServiceImpl extends BaseServiceImpl<ChatGroupBuildingMapper, ChatGroupBuilding> implements IChatGroupBuildingService {

	@Lazy
	private final IMaintainPlanContentService maintainPlanContentService;

	@Lazy
	private final IBuildingExtService buildingExtService;

	@Lazy
	private final IMaintainPlanContentExtService maintainPlanContentExtService;

	@Lazy
	private final IMaintainMalfunctionWorkService malfunctionWorkService;

	@Lazy
	private final ITenantService tenantService;

	@Lazy
	private final MaintainMalfunctionLogService malfunctionLogService;

	@Lazy
	private final IElevatorRepeatFaultConfigService elevatorRepeatFaultConfigService;

	@Lazy
	private final IElevatorWxNumberService elevatorWxNumberService;

	@Lazy
	private final IElevatorWxNumberStatisticService elevatorWxNumberStatisticService;

	private final IBuildingContactsService buildingContactsService;

	private final ILarkMaintenanceService larkMaintenanceService;

	private final String DEFAULT_TENANT_ID = "592800";

	@Override
	@TenantIgnore
	public List<String> getElevatorAddressListByChatroomId(String roomId) {
		return baseMapper.getElevatorAddressListByChatroomId(roomId);
	}

	@Override
	@TenantIgnore
	public List<RobotCreatePlanVO> getElevatorListByChatroomId(RobotCreatePlanDTO robotCreatePlanDTO) {
		return baseMapper.getElevatorListByChatroomId(robotCreatePlanDTO);
	}

	@Override
	@TenantIgnore
	public RobotPlanDetailVO getWorkPlanDetailByPlanId(Long planId) {
		return baseMapper.getWorkPlanDetailByPlanId(planId);
	}

	@Override
	@TenantIgnore
	public List<RobotPlanDetailVO> getWorkPlanListByElevator(Long elevatorId, Date startDate, Date endDate) {
		return baseMapper.getWorkPlanListByElevator(elevatorId, startDate, endDate);
	}

	@Override
	@TenantIgnore
	@Transactional(rollbackFor = Exception.class)
	public Long createWxPlanFromRobot(RobotCreatePlanVO robotCreatePlanVO, RobotCreatePlanDTO robotCreatePlanDTO) {
		// 1. 数据定义与校验
		PlanContentSaveDto planContentSaveDto = new PlanContentSaveDto();
		if(Func.isBlank(robotCreatePlanVO.getGroupTenantId())){
			robotCreatePlanVO.setGroupTenantId(DEFAULT_TENANT_ID);
		}
		if(Func.isNull(robotCreatePlanVO.getElevatorId()) || Func.isNull(robotCreatePlanVO.getBuildingId())){
			throw new ServiceException("无法创建维修工单，电梯信息缺失");
		}
		planContentSaveDto.setBuildingId(robotCreatePlanVO.getBuildingId());
		planContentSaveDto.setElevatorId(robotCreatePlanVO.getElevatorId());
		// 状态值处理 为待分配
		planContentSaveDto.setStatus(TaskStatusEnum.WX_ALLOCATION.getStatus());
		// 固定客户报障
		planContentSaveDto.setWorkOrderType(2);
		//计算维修到达时间
		BuildingExt buildingExt = buildingExtService.getOne(Wrappers.<BuildingExt>lambdaQuery().eq(BuildingExt::getBuildingId, planContentSaveDto.getBuildingId()));
		if (StrUtil.isNotEmpty(buildingExt.getMalfunctionWorkArrivalTime())) {
			//预计达到时间
			long timeMillis = System.currentTimeMillis();
			if (buildingExt.getMalfunctionWorkArrivalTime().contains("m")) {
				long time = Convert.toLong(buildingExt.getMalfunctionWorkArrivalTime().replace("m", "")) * 60 * 1000;
				timeMillis = timeMillis + time;
				Date date2 = new Date(timeMillis);
				planContentSaveDto.setPlanArriveDate(date2);
			} else if (buildingExt.getMalfunctionWorkArrivalTime().contains("h")) {
				long time = Convert.toLong(buildingExt.getMalfunctionWorkArrivalTime().replace("h", "")) * 60 * 60 * 1000;
				timeMillis = timeMillis + time;
				Date date2 = new Date(timeMillis);
				planContentSaveDto.setPlanArriveDate(date2);
			}
		}
		String tenantId = robotCreatePlanVO.getGroupTenantId();
		// 任务主表
		MaintainPlanContent planContent = new MaintainPlanContent();
		DateTime beginDateTime = new DateTime(new Date());
		planContent.setTenantId(tenantId);
		planContent.setPlanDate(beginDateTime);
		planContent.setElevatorId(planContentSaveDto.getElevatorId());
		planContent.setTypeStatus(MaintainPlanContentEnum.MAINTAIN_WX.getId());
		planContent.setStatus(planContentSaveDto.getStatus());
		maintainPlanContentService.save(planContent);

		// 添加维修详情
		MaintainMalfunctionWork work = new MaintainMalfunctionWork();
		work.setPlanId(planContent.getId());
		work.setTenantId(tenantId);
		work.setName("微信群机器人");
		// 根据contracts表获取联系人, 取第一个
		List<BuildingContacts> buildingContactsList = buildingContactsService.list(
			Wrappers.<BuildingContacts>lambdaQuery()
				.eq(BuildingContacts::getBuildingId, planContentSaveDto.getBuildingId())
				.eq(BaseEntity::getIsDeleted, 0)
		);
		if(Func.isEmpty(buildingContactsList)){
			// 当没有联系人时，没有办法给联系值，只能给空字符串
			work.setPhone("");
		}else{
			BuildingContacts buildingContacts = buildingContactsList.get(0);
			work.setPhone(buildingContacts.getPhone());
		}
		// 默认值2
		work.setPlanFrom(2);
		// 默认值12
		work.setProblemItem("12");
		work.setProblemOtherDesc(robotCreatePlanDTO.getReason());
		work.setMfDesc(robotCreatePlanDTO.getReason());
		// 图片路径必传空数组
		work.setMfImgUrl(new ArrayList<>());
		// 其他默认值
		malfunctionWorkService.save(work);
		// 拓展表
		MaintainPlanContentExt maintainPlanContentExt = new MaintainPlanContentExt();
		maintainPlanContentExt.setTenantId(tenantId);
		maintainPlanContentExt.setPlanId(planContent.getId());
		maintainPlanContentExt.setTenantId(tenantId);
		maintainPlanContentExt.setElevatorStop(planContentSaveDto.getIsStop());
		maintainPlanContentExt.setEmerProcType(planContentSaveDto.getEmerProcType());
		maintainPlanContentExt.setWorkOrderType(planContentSaveDto.getWorkOrderType());
		maintainPlanContentExt.setFaultCompany(tenantService.getOne(Wrappers.<Tenant>lambdaQuery().eq(Tenant::getTenantId, tenantId)).getTenantName());
		// 维修工单事件等级
		if (Func.isNotEmpty(planContent.getElevatorId())) {
			ElevatorRepeatFaultConfig faultConfig = elevatorRepeatFaultConfigService.getFaultLevelByElevator(planContent.getElevatorId());
			if (Func.isNotEmpty(faultConfig)) {
					maintainPlanContentExt.setFaultLabel(faultConfig.getTypeDesc());
					maintainPlanContentExt.setFaultLevel(faultConfig.getLevel());
					maintainPlanContentExt.setFaultOvertime(faultConfig.getOvertimeDay());
			}
		}
		maintainPlanContentExtService.save(maintainPlanContentExt);
		//等于待分配插入日志
		malfunctionLogService.insertWorkLog(planContent.getId(), WorkTrackStatusEnum.MALFUNCTION.getTypeName() + "-" + "小程序机器人",TaskStatusEnum.WX_ALLOCATION.getStatus(), null, tenantId);
		// 2024-05-27 新增飞书异步逻辑
		String activeProfile = System.getProperty("spring.profiles.active");
		if ("prod".equals(activeProfile)) {
			larkMaintenanceService.sendRepairLarkMessage(planContent.getId());
		} else {
			larkMaintenanceService.sendRepairLarkMessageCopy(planContent.getId());
		}
		//2024-07-08 新增维修电梯故障次数统计
		Integer workOrderType = Convert.toInt(planContentSaveDto.getWorkOrderType(), -1);
		//2表示客户报障加重复故障
		if (workOrderType == 2) {
			List<ElevatorWxNumber> numbers = elevatorWxNumberService.list(Wrappers.<ElevatorWxNumber>lambdaQuery().ne(ElevatorWxNumber::getStatus, StatusEnum.DISABLE.getId()));
			if (!numbers.isEmpty()) {
				List<Integer> days = numbers.stream().map(ElevatorWxNumber::getDays).distinct().collect(Collectors.toList());
				int max = days.stream().reduce(days.get(0), Integer::max) * -1;
				List<MaintainPlanContent> contentList = maintainPlanContentService.getPlanListOfElevatorId(planContentSaveDto.getElevatorId(),DateUtil.offsetDay(new Date(), max), new Date());
				contentList = contentList.stream().filter(o -> !o.getId().equals(planContent.getId())).collect(Collectors.toList());
				for (ElevatorWxNumber elevatorWxNumber : numbers) {
					Date offsetDay = DateUtil.offsetDay(new Date(), elevatorWxNumber.getDays() * -1);
					int counts = 0;
					for (MaintainPlanContent maintainPlanContent : contentList) {
						if (maintainPlanContent.getCreateTime().after(offsetDay)) {
							counts = counts + 1;
						}
					}
					if (counts >= elevatorWxNumber.getRepetitionCounts()) {
						ElevatorWxNumberStatistic elevatorWxNumberStatistic = new ElevatorWxNumberStatistic();
						elevatorWxNumberStatistic.setTenantId(tenantId);
						elevatorWxNumberStatistic.setElevatorId(planContentSaveDto.getElevatorId());
						elevatorWxNumberStatistic.setWxNumberId(elevatorWxNumber.getId());
						elevatorWxNumberStatistic.setWxNumberDesc(elevatorWxNumber.getTypeDesc());
						elevatorWxNumberStatistic.setPlanId(planContent.getId());
						elevatorWxNumberStatisticService.save(elevatorWxNumberStatistic);
					}
				}
			}
		}
		//2024-11-06 新增维修预警信息
		if (Func.isEmpty(planContentSaveDto.getCheckUsers())) {
			malfunctionWorkService.sendYjMsg(planContentSaveDto, planContent.getId());
		}
		return planContent.getId();
	}

	@Override
	@TenantIgnore
	@Transactional(rollbackFor = Exception.class)
	public Long createKrPlanFromRobot(RobotCreatePlanVO robotCreatePlanVO, RobotCreatePlanDTO robotCreatePlanDTO) {
		// 0. 数据校验、处理，创建救援工单的有一种情况是电梯未知
		if(Func.isBlank(robotCreatePlanDTO.getElevatorAddress())){
			robotCreatePlanVO.setElevatorId(0L);
			robotCreatePlanDTO.setElevatorAddress("电梯未知");
		}
		// 1. 数据定义与校验
		MaintainMalfunctionRescue rescue = new MaintainMalfunctionRescue();
		rescue.setElevatorId(robotCreatePlanVO.getElevatorId());
		rescue.setBuildingId(robotCreatePlanVO.getBuildingId());
		if(Func.isBlank(robotCreatePlanVO.getGroupTenantId())){
			robotCreatePlanVO.setGroupTenantId(DEFAULT_TENANT_ID);
		}
		rescue.setTenantId(robotCreatePlanVO.getGroupTenantId());
		String eventCode = robotCreatePlanDTO.getEventCode();
		if(Func.isNotBlank(eventCode) && RescueNoticeTypeEnum.CHAT_GROUP_AI.getEventCode().equals(eventCode)){
			rescue.setTrapFrom("1_5");
			rescue.setTrapFromValue("微信群报警");
			rescue.setName("微信群机器人");
		}else{
			rescue.setTrapFrom("1_3");
			rescue.setTrapFromValue("梯联网报警");
			rescue.setName("梯联网");
		}
		rescue.setPhone("");
		rescue.setTrapType(0);
		rescue.setTrapDesc(robotCreatePlanDTO.getReason());
		rescue.setAddress(robotCreatePlanDTO.getElevatorAddress());
		return maintainPlanContentService.addRescuePlan(rescue);
	}
}
